/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.h5;

import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dao.Page;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.im.RecvRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.h5.MsnVo;
import cn.easyplatform.messages.vos.h5.PagingVo;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.messages.vos.h5.MessageVo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cn.easyplatform.messages.vos.h5.MessageVo.STATE_READED;
import static cn.easyplatform.messages.vos.h5.MessageVo.STATE_UNREAD;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RecvCmd extends AbstractCommand<RecvRequestMessage> {

	/**
	 * @param req
	 */
	public RecvCmd(RecvRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		BizDao dao = cc.getBizDao();
		List<FieldDo> params = new ArrayList<FieldDo>();
		MessageVo msg = req.getBody();
		if (msg.getMsgid() == 0) {
			StringBuilder sb = new StringBuilder(
					"select a.fromuser,a.groupid,a.msgtime,b.msgtext");
			if (msg.getToUser() != null || msg.getGroup() > 0)
				sb.append(",a.touser,a.msgstatus from sys_chat_detail_info a,sys_chat_info b where a.msgid = b.msgid ");
			else
				sb.append(" from sys_chat_detail_info a,sys_chat_info b where a.msgid = b.msgid ");
			boolean needUpdate = false;
			if (msg.getToUser() != null) {
				// P2P
				sb.append("and ((a.fromuser=? and a.touser=?)||(a.fromuser=? and a.touser=?)) and a.groupid=0");
				params.add(new FieldDo(FieldType.VARCHAR, cc.getUser().getId()));
				params.add(new FieldDo(FieldType.VARCHAR, msg.getToUser()));
				params.add(new FieldDo(FieldType.VARCHAR, msg.getToUser()));
				params.add(new FieldDo(FieldType.VARCHAR, cc.getUser().getId()));
			} else if (msg.getGroup() > 0) {
				// Group
				sb.append("and a.groupid=?");
				params.add(new FieldDo(FieldType.INT, msg.getGroup()));
			} else {
				// 检查所有未读消息
				needUpdate = true;
				sb.append("and a.touser=? and a.msgstatus=?");
				params.add(new FieldDo(FieldType.VARCHAR, cc.getUser().getId()));
				params.add(new FieldDo(FieldType.INT, STATE_UNREAD));
			}
			Page page = new Page(((PagingVo) msg).getPageSize());
			page.setPageNo(((PagingVo) msg).getPageNo());
			page.setGetTotal(false);
			page.setOrderBy("a.msgid");
			List<FieldDo[]> objs = dao.selectList(sb.toString(), params, page);
			sb = null;
			int size = objs.size();
			List<MsnVo> result = new ArrayList<MsnVo>(size);
			for (int i= 0; i < size; i++) {
				FieldDo[] data = objs.get(i);
				MsnVo mv = new MsnVo((String) data[3].getValue());
				mv.setFromUser((String) data[0].getValue());
				mv.setType(msg.getType());
				Number num = (Number) data[1].getValue();
				mv.setGroupId(num.intValue());
				mv.setTime((Date) data[2].getValue());
				if (msg.getFromUser() != null || msg.getGroup() > 0) {
					mv.setToUser((String) data[4].getValue());
					num = (Number) data[5].getValue();
					mv.setStatus(num.intValue());
				} else
					mv.setStatus(STATE_UNREAD);
				result.add(mv);
			}
			if (needUpdate) {
				params.clear();
				params.add(new FieldDo(FieldType.INT, STATE_READED));
				params.add(new FieldDo(FieldType.VARCHAR, cc.getUser().getId()));
				dao.update(
						cc.getUser(),
						"update sys_chat_detail_info set msgstatus=? where touser=?",
						params, true);
			}
			MsnVo[] data = new MsnVo[result.size()];
			result.toArray(data);
			result = null;
			objs = null;
			return new SimpleResponseMessage(data);
		} else {// 有
			params.add(new FieldDo(FieldType.LONG, msg.getMsgid()));
			params.add(new FieldDo(FieldType.VARCHAR, cc.getUser().getId()));
			FieldDo[] data = dao
					.selectOne(
							"select a.fromuser,a.groupid,a.msgtime,b.msgtext from sys_chat_detail_info a,sys_chat_info b where a.msgid = b.msgid and a.msgid=? and a.touser=?",
							params);
			MsnVo[] mv = null;
			if (data != null) {
				mv = new MsnVo[1];
				mv[0] = new MsnVo((String) data[3].getValue());
				mv[0].setFromUser((String) data[0].getValue());
				mv[0].setType(msg.getType());
				Number num = (Number) data[1].getValue();
				mv[0].setGroupId(num.intValue());
				mv[0].setTime((Date) data[2].getValue());
				mv[0].setToUser(cc.getUser().getId());
				params.add(0, new FieldDo(FieldType.INT, STATE_READED));
				dao.update(
						cc.getUser(),
						"update sys_chat_detail_info set msgstatus=? where msgid=? and touser=?",
						params, true);
			}
			return new SimpleResponseMessage(mv);
		}
	}

}
